//
//  YHCashViewController.m
//  YHApp
//
//  Created by -- on 2021/6/19.
//

#import "HACashVC.h"
#import "PORegexTool.h"
#import "HACashInfoModel.h"
#import "HAAccountModel.h"
#import "HACashRecordVC.h"
#import "HAChooseTabPopView.h"
#import "HACashAccountTabPopView.h"
#import "HAAccountVC.h"

@interface HACashVC () <UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableView;
/***/
@property (nonatomic, strong) UITextField *moneyTextField;
/***/
@property (nonatomic, strong) FL_Button *selTypeButton;
/***/
@property (nonatomic, strong) UIImageView *bankIcon;
/***/
@property (nonatomic, strong) UILabel *bankNameLabel;
/***/
@property (nonatomic, strong) UILabel *bankNumLabel;
/***/
@property (nonatomic, strong) HACashInfoModel *model;
/***/
@property (nonatomic, strong) HAAccountModel *accModel;

@end

@implementation HACashVC

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.baseTLabel.text = @"提现";
    [self loadData];

    // Do any additional setup after loading the view.
}

- (void)loadData {
    SYRequest *request = [[SYRequest alloc]init];
    request.requestMethod = SYRequestMethodGET;
    request.requestUrl = @"widthrawa/index";
    [MBProgressHUD showLoading:self.view];
    
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request) {
            [MBProgressHUD hideHUDForView:self.view];
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                self.model = [HACashInfoModel mj_objectWithKeyValues:dataModel.data];
                if (self.model.acc.count > 0) {
                    self.accModel = self.model.acc.firstObject;
                }
                [self setupUI];
                [self.tableView reloadData];
            }else {
                [MBProgressHUD showError:dataModel.msg];
            }
        }
    }];
}


-(void)mitButtonClick {
    [self.view endEditing:YES];
    
    if ([self.moneyTextField.text doubleValue]*100 < 1) {
        [MBProgressHUD showError:@"请输入提现金额"];
        return;
    }
    
    if (self.model.acc.count < 1) {
        [MBProgressHUD showError:@"您还没有添加账号"];
        return;
    }
    
    NSString *type = @"";
    if ([[self.selTypeButton currentTitle] isEqualToString:@"分润金额"]) {
        type = @"1";
    }else if ([[self.selTypeButton currentTitle] isEqualToString:@"返现金额"]) {
        type = @"2";
    }
    
    NSString *acount_type = self.accModel.value;
    
    NSString *total = self.moneyTextField.text ?:@"";
    
    NSDictionary *dict = @{
        @"type":type,
        @"acount_type":acount_type,
        @"total":total,
    };

    SYRequest *request = [[SYRequest alloc]init];
    request.requestMethod = SYRequestMethodPOST;
    request.requestUrl = @"widthrawa/create";
    request.parms = dict;
    [MBProgressHUD showLoading:self.view];
    
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request) {
            [MBProgressHUD hideHUDForView:self.view];
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                [MBProgressHUD showSuccess:@"申请成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }else {
                [MBProgressHUD showError:dataModel.msg];
            }
        }
    }];
}

-(void)listButtonClick {
    HACashRecordVC *vc = [[HACashRecordVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)allButtonClick {
    if ([[self.selTypeButton currentTitle] isEqualToString:@"分润金额"]) {
        self.moneyTextField.text = self.model.wallet_amount;
    }else if ([[self.selTypeButton currentTitle] isEqualToString:@"返现金额"]) {
        self.moneyTextField.text = self.model.wallet_cashback;
    }
}

-(void)selBanksButtonClick {
    WS(weakSelf)
    HACashAccountTabPopView *menu = [[HACashAccountTabPopView alloc]initWithDicts:self.model.acc];
    [menu show];
    menu.YHCashAccountTabMenuSureBlock = ^(HAAccountModel * _Nonnull model) {
        weakSelf.accModel = model;
        [weakSelf.bankIcon sd_setImageWithURL:[NSURL URLWithString:weakSelf.accModel.icon]];
        weakSelf.bankNameLabel.text = weakSelf.accModel.text;
        weakSelf.bankNumLabel.text = weakSelf.accModel.describe;
    };
}

-(void)tipsLabelClick {
    HAAccountVC *vc = [[HAAccountVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)jlButtonClick {
    HACashRecordVC *vc = [[HACashRecordVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 84+15+10+90+10+176+120+54+100;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellID"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCellID"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [self setCellCententView:cell.contentView];
    return cell;}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}

-(void)setCellCententView:(UIView *)contentView {
    for (UIView *view in contentView.subviews) {
        [view removeFromSuperview];
    }
    
    contentView.backgroundColor = [UIColor khaBGColor];

    UIView *bankView = [UIView ha_createView];
    bankView.backgroundColor = [UIColor whiteColor];
    [contentView addSubview:bankView];
    [bankView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_offset(84);
    }];
    
    UIView *topLine = [UIView ha_createView];
    topLine.backgroundColor = [UIColor khaBGColor];
    [bankView addSubview:topLine];
    [topLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_offset(1);
    }];
    
    if (self.model.acc.count > 0) {
        UIImageView *bankIcon = [UIImageView ha_createImageView];
        self.bankIcon = bankIcon;
        [bankIcon sd_setImageWithURL:[NSURL URLWithString:self.accModel.icon]];
        [bankView addSubview:bankIcon];
        [bankIcon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(0);
            make.left.mas_equalTo(25);
            make.width.mas_offset(35);
            make.height.mas_offset(35);
        }];

        UIImageView *rightImageView = [UIImageView ha_createImageView];
        rightImageView.image = [UIImage imageNamed:@"ic_cell_more"];
        [bankView addSubview:rightImageView];
        [rightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_offset(5);
            make.height.mas_offset(10);
            make.centerY.mas_equalTo(0);
            make.right.mas_equalTo(-20);
        }];
        UIButton *selBankButton = [[UIButton alloc]init];
        selBankButton.backgroundColor = [UIColor clearColor];
        [selBankButton addTarget:self action:@selector(selBanksButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [bankView addSubview:selBankButton];
        [selBankButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(rightImageView);
            make.right.mas_equalTo(-15);
            make.width.mas_offset(50);
            make.height.mas_offset(50);
        }];
        
        UILabel *bankNameLabel = [UILabel ha_NLabelWithFont:17 textColor:@"#111A34" text:self.accModel.text alignment:0];
        self.bankNameLabel = bankNameLabel;
        [bankView addSubview:bankNameLabel];
        [bankNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(bankIcon.mas_right).offset(12);
            make.right.mas_equalTo(rightImageView.mas_left).offset(-10);
            make.centerY.mas_equalTo(-10);
        }];

        UILabel *bankNumLabel = [UILabel ha_NLabelWithFont:12 textColor:@"#858B9C" text:self.accModel.describe alignment:0];
        [bankView addSubview:bankNumLabel];
        [bankNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(bankIcon.mas_right).offset(12);
            make.right.mas_equalTo(rightImageView.mas_left).offset(-10);
            make.centerY.mas_equalTo(8);
        }];
    }else {
        UILabel *tipsLabel = [UILabel ha_NLabelWithFont:14 textColor:@"#111A34" text:@"您还没有添加账号,去添加?" alignment:0];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tipsLabelClick)];
        [tipsLabel addGestureRecognizer:tap];
        tipsLabel.userInteractionEnabled = YES;
        [bankView addSubview:tipsLabel];
        [tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(40);
            make.centerY.mas_equalTo(0);
        }];
    }
    
    UIView *mainView = [UIView ha_createView];
    mainView.backgroundColor = [UIColor whiteColor];
    [contentView addSubview:mainView];
    [mainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(bankView.mas_bottom).offset(15);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_offset(10+90+10+176);
    }];
        
    UIView *moneyView = [UIView ha_createView];
    moneyView.layer.cornerRadius = 6;
    moneyView.layer.masksToBounds = YES;
    moneyView.backgroundColor = [UIColor colorWithHexString:@"#9E312E"];
    [mainView addSubview:moneyView];
    [moneyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(10);
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.height.mas_offset(90);
    }];
    
    UILabel *moneyLTitLabel = [UILabel ha_NLabelWithFont:14 textColor:@"#FFFFFF" text:@"分润金额(元)" alignment:0];
    [moneyView addSubview:moneyLTitLabel];
    [moneyLTitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(15);
        make.left.mas_equalTo(20);
        make.width.mas_offset((kUIScreen_w-80)*0.5);
    }];
    
    UILabel *moneyLNumLabel = [UILabel ha_BLabelWithFont:20 textColor:@"#FFFFFF" text:self.model.wallet_amount alignment:0];
    [moneyView addSubview:moneyLNumLabel];
    [moneyLNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-15);
        make.left.mas_equalTo(20);
        make.width.mas_offset((kUIScreen_w-80)*0.5);
    }];


    UILabel *moneyRTitLabel = [UILabel ha_NLabelWithFont:14 textColor:@"#FFFFFF" text:@"返现金额(元)" alignment:2];
    [moneyView addSubview:moneyRTitLabel];
    [moneyRTitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(15);
        make.right.mas_equalTo(-20);
        make.width.mas_offset((kUIScreen_w-80)*0.5);
    }];
    
    UILabel *moneyRNumLabel = [UILabel ha_BLabelWithFont:20 textColor:@"#FFFFFF" text:self.model.wallet_cashback alignment:2];
    [moneyView addSubview:moneyRNumLabel];
    [moneyRNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-15);
        make.right.mas_equalTo(-20);
        make.width.mas_offset((kUIScreen_w-80)*0.5);
    }];

    
    UILabel *titLabel = [UILabel ha_NLabelWithFont:19 textColor:@"#111A34" text:@"转出金额(元)" alignment:0];
    [mainView addSubview:titLabel];
    [titLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(25);
        make.top.mas_equalTo(moneyView.mas_bottom).offset(30);
        make.height.mas_offset(20);
    }];

    FL_Button *selTypeButton = [[FL_Button alloc]initWithAlignmentStatus:FLAlignmentStatusCenter];
    self.selTypeButton = selTypeButton;
    [selTypeButton setTitle:@"分润金额" forState:UIControlStateNormal];
    [selTypeButton setTitleColor:[UIColor colorWithHexString:@"#858B9C"] forState:UIControlStateNormal];
    selTypeButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [selTypeButton setImage:[UIImage imageNamed:@"ha_12"] forState:UIControlStateNormal];
    selTypeButton.fl_padding = 6;
    [selTypeButton addTarget:self action:@selector(selTypeButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [mainView addSubview:selTypeButton];
    [selTypeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(titLabel);
        make.right.mas_equalTo(-25);
        make.width.mas_offset(82);
        make.height.mas_offset(32);
    }];

    UIView *lineView = [UIView ha_createView];
    lineView.backgroundColor= [UIColor kLineColor];
    [mainView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(25);
        make.right.mas_equalTo(-25);
        make.bottom.mas_offset(-60);
        make.height.mas_offset(0.8);
    }];

    UIButton *allButton = [[UIButton alloc]init];
    [allButton setTitle:@"全部提出" forState:UIControlStateNormal];
    [allButton setTitleColor:[UIColor colorWithHexString:@"#5F67FC"] forState:UIControlStateNormal];
    allButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [allButton addTarget:self action:@selector(allButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [mainView addSubview:allButton];
    [allButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.bottom.mas_equalTo(lineView.mas_top).offset(-10);
        make.width.mas_offset(68);
        make.height.mas_offset(32);
    }];

    UITextField *textField = [[UITextField alloc]init];
    textField.delegate = self;
    textField.textColor = [UIColor colorWithHexString:@"#333333"];
    textField.font = [UIFont systemFontOfSize:18];
    textField.placeholder = [NSString stringWithFormat:@"最多%@元",self.model.wallet_amount];
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.keyboardType = UIKeyboardTypeDecimalPad;
    textField.textAlignment = NSTextAlignmentLeft;
    [mainView addSubview:textField];
    self.moneyTextField = textField;
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(25);
        make.right.mas_equalTo(allButton.mas_left);
        make.centerY.mas_equalTo(allButton);
        make.height.mas_offset(30);
    }];
    
    NSString *remark= [self.model.config_remark stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    UILabel *ex1Label = [UILabel ha_NLabelWithFont:12 textColor:@"#858B9C" text:remark alignment:0];
    ex1Label.numberOfLines = 0;
    [mainView addSubview:ex1Label];
    [ex1Label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(25);
        make.right.mas_equalTo(-25);
        make.top.mas_equalTo(lineView.mas_bottom).offset(10);
    }];
    
    if (HAUserDefaults.isLock == 1) {
        UIButton *jlButton = [[UIButton alloc]init];
        [jlButton setTitle:@"提现记录" forState:UIControlStateNormal];
        [jlButton setTitleColor:[UIColor colorWithHexString:@"#5F67FC"] forState:UIControlStateNormal];
        jlButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [jlButton addTarget:self action:@selector(jlButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [contentView addSubview:jlButton];
        [jlButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(20);
            make.top.mas_equalTo(mainView.mas_bottom).offset(10);
            make.width.mas_offset(68);
            make.height.mas_offset(32);
        }];
    }


    UIButton *mitButton = [[UIButton alloc]init];
    [mitButton setTitle:@"确认提交" forState:UIControlStateNormal];
    [mitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    mitButton.titleLabel.font = [UIFont systemFontOfSize:16];
    mitButton.backgroundColor = [UIColor colorWithHexString:@"#000000"];
    mitButton.layer.cornerRadius = 4;
    mitButton.layer.masksToBounds = true;
    [mitButton addTarget:self action:@selector(mitButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:mitButton];
    [mitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(42);
        make.right.mas_equalTo(-42);
        make.top.mas_equalTo(mainView.mas_bottom).offset(120);
        make.height.mas_offset(44);
    }];

    FL_Button *listButton = [[FL_Button alloc]init];
    [listButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [listButton setTitle:@"申请记录" forState:UIControlStateNormal];
    listButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [listButton setTitleColor:[UIColor colorWithHexString:@"#5F67FC"] forState:UIControlStateNormal];
    [listButton addTarget:self action:@selector(listButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:listButton];
    [listButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset(88);
        make.height.mas_offset(34);
        make.top.mas_equalTo(mitButton.mas_bottom).offset(15);
        make.centerX.mas_equalTo(0);
    }];

}

-(void)setupUI {
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(app_topH+44);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
}

- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
        // 去掉滚动条
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        // 设置背景颜色
        _tableView.backgroundColor = [UIColor khaBGColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

-(void)allMoneyCashClick {
    self.moneyTextField.text = @"999.88";
}

-(void)selTypeButtonClick {
    WS(weakSelf)
    NSMutableArray *dicts = [NSMutableArray array];
    [dicts addObject:@{@"color":@"#373737",@"title":@"分润金额"}];
    [dicts addObject:@{@"color":@"#373737",@"title":@"返现金额"}];
    HAChooseTabPopView *menu = [[HAChooseTabPopView alloc]initWithDicts:dicts title:@"提现类型"];
    [menu show];
    menu.YHChooseTabMenuCellBlock = ^(NSString * _Nonnull title) {
        [weakSelf.selTypeButton setTitle:title forState:UIControlStateNormal];
        weakSelf.moneyTextField.text = @"";
        if ([title isEqualToString:@"分润金额"]) {
            weakSelf.moneyTextField.placeholder = [NSString stringWithFormat:@"最多%@元",weakSelf.model.wallet_amount];
        }else if ([title isEqualToString:@"返现金额"]) {
            weakSelf.moneyTextField.placeholder = [NSString stringWithFormat:@"最多%@元",weakSelf.model.wallet_cashback];
        }
    };
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (textField == self.moneyTextField) {
        
        NSString *textStr = textField.text;
        NSString *t = [NSString stringWithFormat:@"%@%@",textStr,string];
        //已经包含小数点时，无视输入小数点
        if([textStr rangeOfString:@"."].location != NSNotFound) {
            if([string isEqualToString:@"."]){
                return NO;
            }
        }
        if (t.length > 0) {
            BOOL isPoint = [PORegexTool checkInputFristPoint:[t substringToIndex:1]];
            if (isPoint) {
                self.moneyTextField.text = @"0.";
                return NO;
            }
        }
        //限制输入小数点和数字
        BOOL isT1 = [PORegexTool checkInputOnlyPointNumber:t];
        
        //检测小数点后面是否满2位
        BOOL isT2 = [PORegexTool checkAfterPointLenth:t];
        
        if (!isT2 && isT1) {
            return YES;
        }else{
            return NO;
        }
    }
    
    return YES;
}



@end
